﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;

namespace Site_Extractor
{
	public class ForumNana
	{
		private static string
			_mainLink = "http://forums.nana10.co.il/Category/?CategoryID=245&TypeID=1",
			_linkPrefix = "http://forums.nana10.co.il/forum/?forumid=",
			_linkForum = "http://forums.nana10.co.il/Forum/MessagesList.asp?";
		private static string[] _toRemove = { "\r", "\n", "\t" };
			
		public static List<string> GetAllForumLinks()
		{
			var res = ForumHandler.GatherAllLinks(_mainLink, isForumMine);
			var links = new List<string>();
			foreach (string link in res)
			{
				var splitted = link.Split('?');
				if (splitted.Length != 2) continue;
				var id = splitted[1];
				links.Add(string.Format("{0}{1}", _linkForum, id));
			}
			return links;
		}
		public static List<string> GetAllMessageLinks(string forumLink)
		{
			var page = HtmlDownloader.DownloadPage(new Uri(forumLink));
			List<string> msgLinks = ForumHandler.GetFromString(page, "if( iMsgAr != null )", "</script>");

			return msgLinks;
		}
		private static bool isForumMine(string link)
		{
			if (link.ToLower().Contains("pid")) return false;
			if (!link.ToLower().StartsWith(_linkPrefix)) return false;
			return true;
		}

		public static ForumMessage GetMessage(string messageLink)
		{
			ForumMessage msg = new ForumMessage();

			foreach(string s in _toRemove) messageLink=messageLink.Replace(s,string.Empty);
			var pdt = ForumHandler.GetFromString(messageLink, "pDT(", ");");
			if (pdt.Count == 0) return msg;

			var id = ForumHandler.GetFromString(messageLink, "oCurrNode=pAN(oCurrNode,", ");");
			if (id.Count > 0)
			{
				long.TryParse(id[0], out msg.UniqueId);
			}
			else
			{
				id = ForumHandler.GetFromString(messageLink, "iMsgAr[iMsgAr.length-1][\"ID\"]=", ";");
				if (id.Count > 0)
				{
					long.TryParse(id[0], out msg.UniqueId);
				}
			}

			var args = ForumHandler.GetFromString(pdt[0], "'", "',");

			DateTime date;
			ForumHandler.GetDate(args[1], "HH:mm dd/MM/yy", out date);
			msg.Date = date;
			if (args.Count == 8)
			{
				msg.Text = args[7];
				msg.Topic = args[6];
			}
			else if (args.Count == 7)
			{
				msg.Text = args[6];
				msg.Topic = args[5];
			}

			return msg;
		}
	}
}
